package com.spacex.danhuang.polive.fragments;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.spacex.danhuang.polive.AppDataClass.AllShowUserData;
import com.spacex.danhuang.polive.Application.VApplication;
import com.spacex.danhuang.polive.Constants.Constants;
import com.spacex.danhuang.polive.R;
import com.spacex.danhuang.polive.adapters.AllShowAdapter;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import io.socket.client.Socket;

/**
 * A simple {@link Fragment} subclass.
 */
public class AllShowFragment extends AppBaseFragment {
    private static final String TAG = "AllShowFragment";

    private VApplication app;
    private Socket mSocket;

    private static AllShowFragment allShowFragment = null;

    private RecyclerView mRecyclerView;
    private List<AllShowUserData> allShowDataList;
    private AllShowAdapter allShowDataAdapter;

    private int mUserRole;

    private String mRoomName = "";

    public AllShowFragment() {
        // Required empty public constructor
    }

    public static AllShowFragment getInstance() {
        if (allShowFragment == null) {
            allShowFragment = new AllShowFragment();
        }
        return allShowFragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        ViewGroup viewGroup = (ViewGroup) inflater.inflate(R.layout.fragment_all_show, container, false);

        app = (VApplication)getActivity().getApplication();
        mSocket = app.getSocket();
        mUserRole = app.getUserRole();

        return viewGroup;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        initView();
    }

    private void initView() {
        mRecyclerView = (RecyclerView) getActivity().findViewById(R.id.rv_all_show);

        allShowDataList = new ArrayList<AllShowUserData>();
        allShowDataAdapter = new AllShowAdapter(allShowDataList);
        mRecyclerView.setLayoutManager(new GridLayoutManager(getActivity(), 2));
        mRecyclerView.setAdapter(allShowDataAdapter);

        allShowDataAdapter.setOnItemClickListener(new AllShowAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                AllShowUserData clickUserData = allShowDataList.get(position);
                String roomname = clickUserData.getNickname();
                String roomid = clickUserData.getUserId();
                Log.i(TAG, "roomid = "+roomid);

                app.setRoomName(roomname);
                attemptJoinRoom(roomid);
            }
        });

        attemptAllList();
    }

    /**
     * request for current list of hot shows
     * data: null
     **/
    private void attemptAllList() {

        JSONObject attemptHotListJSON = new JSONObject();
        try {
            attemptHotListJSON.put("request", Constants.GET_HOT_LIST_NAME);
            attemptHotListJSON.put("data", "");
        } catch (JSONException e) {
            e.printStackTrace();
        }

        String tmpHotListStr = attemptHotListJSON.toString();
        Log.i(TAG, "get hot list send");
        Log.i(TAG, tmpHotListStr);
        mSocket.send(tmpHotListStr);
    }

    /**
     * request for join a room with data(roomid)
     * @param roomid
     **/
    private void attemptJoinRoom(String roomid) {

        JSONObject attempJoinRoomJSON = new JSONObject();
        JSONObject attempJoinRoomData = new JSONObject();
        try {
            attempJoinRoomJSON.put("request", Constants.JOIN_ROOM_NAME);

            attempJoinRoomData.put("roomid", roomid);
            attempJoinRoomJSON.put("data", attempJoinRoomData);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        String tmpJoinRoomStr = attempJoinRoomJSON.toString();
        Log.i(TAG, "join room send");
        Log.i(TAG, tmpJoinRoomStr);
        mSocket.send(tmpJoinRoomStr);
    }

    @Override
    protected void handleSwitchMethod(String rsp_name, int rsp_status, String rsp_errmsg, JSONObject onHandleMsgData) {
        switch (rsp_name) {
            case Constants.GET_HOT_LIST_NAME:
                Log.i(TAG, "handleHotList");
                handleAllList(rsp_status, rsp_errmsg, onHandleMsgData);
                break;
            default:
                Log.i(TAG, "no rsp name");
        }
    }

    private void handleAllList(final int status, final String errmsg, final JSONObject data) {
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (status != 0) {
                    Toast.makeText(getActivity().getApplicationContext(),
                            "ERROR: "+errmsg, Toast.LENGTH_SHORT).show();
                    return;
                }

                //清空之前保存的直播列表信息
                allShowDataList.clear();

                JSONArray allshow_rsp_list;
                try {
                    if (data == null) {
                        Toast.makeText(getActivity().getApplicationContext(),
                                "获取roomid失败", Toast.LENGTH_SHORT).show();

                        AllShowUserData showData = new AllShowUserData();
                        showData.setUserId("no roomid");
                        showData.setNickname("no show");
                        allShowDataList.add(showData);
                        allShowDataAdapter.notifyDataSetChanged();

                        return;
                    }
                    allshow_rsp_list = data.getJSONArray("hotliveshowlist");

                    if (allshow_rsp_list.length() > 0) {
                        for (int i=0; i<allshow_rsp_list.length(); i++) {
                            JSONObject tmpShowJSON = allshow_rsp_list.getJSONObject(i);
                            Log.i(TAG, "roomid = "+tmpShowJSON.getString("roomid"));
                            Log.i(TAG, "nickname = "+tmpShowJSON.getString("nickname"));

                            AllShowUserData showData = new AllShowUserData();
                            showData.setUserId(tmpShowJSON.getString("roomid"));
                            showData.setNickname(tmpShowJSON.getString("nickname"));
                            allShowDataList.add(showData);
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                if (allShowDataList.size() > 0) {
                    Log.i(TAG, "list content changed, update the RecyclerView");
                }
                if (allShowDataList.size() == 0) {
                    Log.i(TAG, "no show currently");
                    AllShowUserData showData = new AllShowUserData();
                    showData.setUserId("no roomid");
                    showData.setNickname("no show");
                    allShowDataList.add(showData);
                }

                allShowDataAdapter.notifyDataSetChanged();
            }
        });
    }

}
